// pages/plan/plan.js
import util from "../../utils/util.js"
import http from "../../utils/http.js"

let scrollWeightTimer = null
let scrollHeightTimer = null
var app = getApp()
Page({

  /**
   * 页面的初始数据
   */
  data: {
    active: 0,
    sexShow: false,
    sex: "",
    birthdayShow:false,
    birthday: '',
    heightShow: false,
    height: '',
    healthShow: false,
    health: '',
    healthFormatted: "",
    predilectionShow:false, // 偏好
    waterPredilection: '',
    waterPredilectionName: "",
    jobPropertyShow: false, //职业 
    jobProperty: '',
    jobPropertyFormatted: "",
    weightShow: false,
    weight: "",// 最终选中的体重
    weightFormatted: "",
    sexs:[{
      text: '男',
      value: 0
    },{
      text: '女',
      value: 1
    }],
    healths:[],
    jobPropertys: [],
    maxDate: new Date().getTime(),
    minDate: new Date("1900-01-01").getTime(),
    defultDate: new Date("1990-03-11").getTime(),
    formatter(type, value) {
      if (type === 'year') {  
        return `${value}年`;
      } else if (type === 'month') {
        return `${value}月`;
      }
      return `${value}日`;
    },
    drinkNum: 0,   // 推荐饮水量
    targetNum: '', // 目标饮水量
    weightValue: '50.0', // 测量尺的默认体重值
    weightNum: 2000 + 42 * app.globalData.screenScale, //测量尺刻度的数量
    scrollLeft: 4550,
    intoId: 'id1000',
    heightValue: "0", // 测量尺的默认身高值
    scrollLeft1: '0',
    heightNum: 240 + 42 * app.globalData.screenScale, //测量尺刻度的数量
    tagList:[],
    tagActives: [],
    wakeUpTime: '',
    wakeUpTimeShow: false,
    sleepTime: "",
    sleepTimeShow: false,
    timeType: "",
    timeTypeShow: false,
    warnTime: "",
    warnTimeShow: false,
    warnType: "",
    warnTypeShow: false,
    timeTypes:[{
      text: "时间点",
      id: 1
    },
    {
      text: "时间段",
      id: 2
    }],
    timeTypeTxt: "",
    warnTypes:[{
      text: "模板消息",
      id: 1
    }],
    warnTypeTxt: ""
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    // 偏好设定
    this.getInfo()
    // 饮水方案
    this.getSetInfo()
    this.setData({
      jobPropertys: app.globalData.jobProperty,
      tagList: app.globalData.drinkPredilection,
      healths: app.globalData.health
    })
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    let warnTime = app.globalData.warnTime
    if (warnTime){
      this.setData({
        warnTime
      })
    }
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {
    return {
      title: app.globalData.shareTitle,
      path: '/pages/index/index'
    }
  },
  getInfo(){
    http.request("/machineManage/setting")
    .then(res=>{
      console.log(res.data.waterPredilection.split(","))
      this.setData({
        sex: res.data.sex,
        birthday: res.data.birthday,
        birthdayFormatted: res.data.birthdayFormatted,
        health: res.data.health,
        healthFormatted: res.data.healthFormatted,
        height: res.data.height,
        weight: res.data.weight,
        weightFormatted: res.data.weightFormatted,
        jobProperty: res.data.jobProperty, // 职业
        jobPropertyFormatted: res.data.jobPropertyFormatted,
        waterPredilection: res.data.waterPredilection, // 偏好
        waterPredilectionName: res.data.waterPredilectionName,
        targetNum: res.data.waterQuantityPlan,
        drinkNum: res.data.recommendWaterQuantity,
        tagActives: res.data.waterPredilection.split(",")
      })
    })
    .catch(res=>{

    })
  },
  getSetInfo(){
    http.request("/userReminder/index")
    .then(res=>{
      let timeTypeTxt = ""
      for (let i = 0; i < this.data.timeTypes.length; i++) {
        if (this.data.timeTypes[i].id == res.data.warnSettingType){
          timeTypeTxt = this.data.timeTypes[i].text
          break
        }
      }
      let warnTypeTxt = ""
      for (let i = 0; i < this.data.warnTypes.length; i++) {
        if (this.data.warnTypes[i].id == res.data.warnType) {
          warnTypeTxt = this.data.warnTypes[i].text
          break
        }
      }
      this.setData({
        wakeUpTime: res.data.wakeUpTime,
        sleepTime: res.data.sleepTime,
        timeType: res.data.warnSettingType,
        timeTypeTxt: timeTypeTxt,
        warnTime: res.data.warnTime,
        warnType: res.data.warnType,
        warnTypeTxt: warnTypeTxt
      })
    })
    .catch(res=>{

    })
  },
  select(e){
    let id = e.currentTarget.dataset.id
    this.setData({
      active: id
    })
  },
  onClose(){
    this.setData({
      sexShow: false,
      birthdayShow: false,
      heightShow: false,
      healthShow: false,
      waterPredilectionShow: false, // 偏好
      tagActives: this.data.waterPredilection.split(","), // 偏好 tag 清空
      jobPropertyShow: false, //职业 
      weightShow: false,
      wakeUpTimeShow: false,
      sleepTimeShow: false,
      timeTypeShow: false,
      warnTimeShow: false,
      warnTypeShow: false
    })
  },
  openSexShow(){
    this.setData({
      sexShow: true
    })
  },
  openBirthdayShow(){
    this.setData({
      birthdayShow: true
    })
  },
  openHeightShow(){
    this.setData({
      heightShow: true
    })
  },
  openHealthShow(){
    this.setData({
      healthShow: true
    })
  },
  openWaterPredilectionShow(){
    this.setData({
      waterPredilectionShow: true
    })
  },  
  openJobPropertyShow(){
    this.setData({
      jobPropertyShow: true
    })
  },   
  openWeightShow(e){
    this.setData({
      weightShow: true,
    })
    setTimeout(() => {
      this.setData({
        scrollLeft: 4550
      })
    }, 100);
    // wx.nextTick(() => {
    //   this.setData({
    //     scrollLeft: 4550
    //   })
    // })
  },
  sexConfirm(e) {
    this.setData({ 
      sexShow: false,
      sex: e.detail.value.value
    });
  },
  healthConfirm(e) {
    this.setData({ 
      healthShow: false,
      health: e.detail.value.value,
      healthFormatted: e.detail.value.text
    });
  },
  setTag(e){
    let value = e.currentTarget.dataset.val
    let tagActives = this.data.tagActives
    let index = tagActives.indexOf(value)
    if( index == -1){ // 未高亮
      tagActives.push(value)
    }else{
      tagActives.splice(index, 1)
    }
    this.setData({
      tagActives
    })
  },
  waterPredilectionConfirm(){
    let waterPredilection = ""
    let waterPredilectionName = ""
    let tagActives = this.data.tagActives
    for(let i = 0; i < tagActives.length;i++) {
      waterPredilectionName +=  ((i == 0 ? '' : '、') + this.data.tagList[tagActives[i]].text) 
      waterPredilection = this.data.tagActives.join(",")
    }
    this.setData({
      waterPredilectionShow: false,
      waterPredilection,
      waterPredilectionName
    })
  },
  jobPropertyConfirm(e){
    this.setData({ 
      jobPropertyShow: false,
      jobPropertyFormatted: e.detail.value.text,
      jobProperty: e.detail.value.value
    });
  },
  dateConfirm(e){
    let date = e.detail
    this.setData({
      birthday: date / 1000,
      birthdayFormatted: util.formatDate(new Date(date)),
      birthdayShow: false
    })
  },
  dateCancel(){
    this.setData({
      birthdayShow: false
    })
  },
  scrollChange(e) {
    let scale = 1 //app.globalData.screenScale
    let scrollLeft = e.detail.scrollLeft
    let unit = (18/2)*scale
    // console.log('scale',scale)
    console.log(e)
    let unit10 = (unit*10+1) // 每10个小格子的长度
    let weightValue1 = parseInt(scrollLeft / unit10) // 整数位
    let weightValue2 = parseInt(scrollLeft % unit10 -1)/unit // 小数位
    // console.log("weightValue1",weightValue1)
    // console.log("weightValue2",weightValue2)
    let weightValue = (weightValue1 + weightValue2/10).toFixed(1)
    weightValue = weightValue > 0 ? weightValue : 0
    this.setData({
      weightValue: weightValue
    })
    // 200 毫秒后修正
    if(scrollWeightTimer){
      clearTimeout(scrollWeightTimer)
    }
    // 修正真实的刻度
    let ruleValue = weightValue*10
    scrollLeft = parseInt(ruleValue/10) * unit10 +  ruleValue % 10 * unit + 1
    
    scrollWeightTimer = setTimeout(() => {
      this.setData({
        scrollLeft
      })
    }, 200);
  },
  scrollHeightChange(e) {
    let scale = 1 //app.globalData.screenScale
    let scrollLeft = e.detail.scrollLeft
    let unit = (18/2)*scale
    // console.log('scale',scale)
    console.log(new Date().getTime())
    let unit10 = (unit*10+1) // 每10个小格子的长度
    let heightValue1 = parseInt(scrollLeft / unit10)*10 // 整数位
    let heightValue2 = parseInt(scrollLeft % unit10 -1)/unit  // 小数位
    heightValue2 = heightValue2 >= 0 ? heightValue2 : 0

    let heightValue =  Math.round(heightValue1 + heightValue2)
    this.setData({
      heightValue
    })
    // 200 毫秒后修正
    if(scrollHeightTimer){
      clearTimeout(scrollHeightTimer)
    }
    // 修正真实的刻度
    let ruleValue = heightValue
    scrollLeft = parseInt(ruleValue/10) * unit10 +  ruleValue % 10 * unit + 1
    
    scrollHeightTimer = setTimeout(() => {
      this.setData({
        scrollLeft1: scrollLeft
      })
    }, 200);
  },  
  weightChange(){
    this.setData({
      weight: this.data.weightValue,
      weightFormatted: this.data.weightValue+'KG',
      weightShow: false,
      drinkNum: 40 * this.data.weightValue
    })
  },
  heightChange(){
    this.setData({
      height: this.data.heightValue,
      heightShow: false
    })  
  },
  targetChange(e){
    this.setData({
      targetNum: e.detail.value
    })
  },
  submit(){
    let params = {
      sex: this.data.sex,
      birthday: this.data.birthday,
      height: this.data.height,
      health: this.data.health,
      weight: this.data.weight,
      jobProperty: this.data.jobProperty,
      waterPredilection: this.data.waterPredilection,
      recommendWaterQuantity: this.data.drinkNum,
      waterQuantityPlan: this.data.targetNum
    }
    http.request("/machineManage/saveSetting", params)
      .then(res => {
        wx.showToast({
          title: res.message,
          icon: 'none'
        })
      })
      .catch(res => {

      })
  },
  openWakeUpTimeShow(){
    this.setData({
      wakeUpTimeShow: true
    })
  },
  openSleepTimeShow(){
    this.setData({
      sleepTimeShow: true
    })
  },
  openTimeTypeShow(){
    this.setData({
      timeTypeShow: true
    })
  },
  naviToWarnTime(){
    wx.navigateTo({
      url: '/pages/warnTime/warnTime?type=' + this.data.timeType
    })
    wx.setStorageSync('warnTime', this.data.warnTime)
  },
  openWarnTypeShow(){
    this.setData({
      warnTypeShow: true
    })
  },
  wakeUpTimeConfirm(e){
    this.setData({
      wakeUpTime: e.detail,
      wakeUpTimeShow: false
    })
  },
  sleepTimeConfirm(e){
    this.setData({
      sleepTime: e.detail,
      sleepTimeShow: false
    })
  },
  timeTypeConfirm(e){
    let timeType = e.detail.value.id
    let timeTypeTxt = e.detail.value.text
    this.setData({
      timeType: timeType,
      timeTypeTxt,
      timeTypeShow: false
    })
  },
  warnTypeConfirm(e){
    let warnType = e.detail.value.id
    let warnTypeTxt = e.detail.value.text
    this.setData({
      warnType: warnType,
      warnTypeTxt,
      warnTypeShow: false
    })
  },
  // 饮水提醒保存
  submitWarn(){
    let params = {
      wakeUpTime: this.data.wakeUpTime,
      sleepTime: this.data.sleepTime,
      warnSettingType: this.data.timeType,
      warnTime: this.data.warnTime,
      warnType: this.data.warnType
    }
    wx.requestSubscribeMessage({
      tmplIds: ['22zciaYGgf-qpsapBVTwnjqN4KsklvoVddUaWotZ29Y'],
      success (res) { }
    })
    http.request("/userReminder/save",params)
    .then(res=>{
      wx.showToast({
        title: res.message,
        icon: 'none'
      })
    })
    .catch(res=>{

    })
  }
})